package com.example.aigc_education.security.handle;

import com.alibaba.fastjson.JSON;
import com.example.aigc_education.security.domain.LoginUser;
import com.example.aigc_education.security.service.TokenService;
import com.example.aigc_education.utils.ResultUtil;
import com.example.aigc_education.utils.WebUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义登出成功处理器
 */
@Component
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {

    @Resource
    private TokenService tokenService;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (loginUser != null) {
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());

        }
        WebUtil.renderString(response, JSON.toJSONString(ResultUtil.success("退出成功")));
    }
}
